package com.yaowk.system.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.tx.Tx;
import com.jfinal.plugin.activerecord.tx.TxConfig;
import com.jfinal.upload.UploadFile;
import com.yaowk.common.kit.Constant;
import com.yaowk.common.kit.ResultKit;
import com.yaowk.system.model.FileUpload;

import java.util.*;

/**
 * 文件上传
 *
 * @authc yaowk
 * 2017/5/1
 */
public class FileController extends Controller {

    /**
     * 文件上传
     *
     * @title 文件上传
     */
    @Before(Tx.class)
    @TxConfig(Constant.SYSTEM_MODULE)
    public void upload() {
        List<UploadFile> uploadFileList = getFiles();
        Map<String, FileUpload> map = new HashMap<>();
        String basePath = getSession().getServletContext().getContextPath() + "/upload/";
        Date time = new Date();
        for (UploadFile uploadFile : uploadFileList) {
            FileUpload fileUpload = new FileUpload();
            fileUpload.setPath(basePath + uploadFile.getFileName()).setName(uploadFile.getOriginalFileName()).setTime(time).save();
            map.put(uploadFile.getParameterName(), fileUpload);
        }
        renderJson(ResultKit.success(map));
    }

    /**
     * 文件上传
     *
     * @title 文件上传返回list
     */
    @Before(Tx.class)
    @TxConfig(Constant.SYSTEM_MODULE)
    public void uploadToList() {
        List<UploadFile> uploadFileList = getFiles();
        String basePath = getSession().getServletContext().getContextPath() + "/upload/";
        Date time = new Date();
        List<FileUpload> path = new ArrayList<>();
        for (UploadFile uploadFile : uploadFileList) {
            FileUpload fileUpload = new FileUpload();
            fileUpload.setPath(basePath + uploadFile.getFileName()).setName(uploadFile.getOriginalFileName()).setTime(time).save();
            path.add(fileUpload);
        }
        renderJson(ResultKit.success(path));
    }
}
